# -*- coding: utf-8 -*-
"""
@File    : ningxia_yinchuan_hqzq_policy
@Author  : caojy
"""
import datetime
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class NingxiayinchuanHqzqPolicy(BaseTaxPolicySpider):
    name = 'ningxia_yinchuan_hqzq_policy'

    province = '宁夏回族自治区'
    city = '银川市'
    county = ''
    park = ''
    url = 'https://www.gov.cn/zhengce/qiye/EnterprisePpolicyLibrary?lifeCycle='
    custom_settings = {
        "DEFAULT_REQUEST_HEADERS": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
            "Content-Type": "application/json",
        }
    }

    def start_requests(self):
        for source, county, url in [
            ['银川市人民政府', '', 'https://www.gov.cn/zhengce/qiye/trssearch/search/all'],
        ]:
            data = {
                "dbname": "",
                "currpage": 1,
                "pagesize": 100,
                "searchWord": "",
                "searchField": "title",
                "searchSort": "time",
                "DocType": "",
                "publishDept": "",
                "hqType": "",
                "enterpriseType": "",
                "enterpriseScale": "",
                "lifeCycle": 0
            }
            json_data = json.dumps(data, separators=(',', ':'))
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, method='POST', body=json_data, callback=self.parse_list, meta={"item": item, "data": data})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        datas = response.json()['data']
        for elem in datas['list']:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['publishDocTime']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jhtm' not in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = datas['totalPages']
            print(response.url, "page:", total_page)
            data = response.meta['data']
            url = response.url
            for page_num in range(2, int(total_page) + 1):
                data['currpage'] = page_num
                json_data = json.dumps(data, separators=(',', ':'))
                yield scrapy.Request(url, method='POST', body=json_data, callback=self.parse_list, dont_filter=True,
                                     meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl ningxia_yinchuan_hqzq_policy".split())
